﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media;
using System.Threading;
using Microsoft.Xna.Framework;
using System.Windows.Threading;
using System.Windows.Media.Imaging;

namespace iMusik
{
    public enum MEDIA
    {
        SONG,
        ARTIST,
        ALBUM,
        FAVORITE,
        SDCARD,
        SEARCH
    };

    public partial class PhonePage1 : PhoneApplicationPage
    {
        private bool _IsLoadedSong;
        private bool _IsLoadedArtist;
        private bool _IsLoadedAlbum;
        DispatcherTimer _timer;
        private System.Windows.Point _MouseDownPoint;
        private System.Windows.Point _MouseUpPoint;
        private MEDIA _CurrentMedia;
        private ImageBrush _SongImage;


        public PhonePage1()
        {
            InitializeComponent();

            _IsLoadedSong = false;
            _IsLoadedArtist = false;
            _IsLoadedAlbum = false;
            _timer = new DispatcherTimer();
            _timer.Tick += timer_Tick;
            MediaPlayer.MediaStateChanged += _OnMediaStateChanged;
            MediaPlayer.ActiveSongChanged += _OnActiveSongChanged;
            _CurrentMedia = MEDIA.SEARCH;
            _MouseDownPoint = new System.Windows.Point();
            _MouseUpPoint = new System.Windows.Point();

            _SongImage = new ImageBrush();
            _SongImage.ImageSource = new BitmapImage(new Uri(@"/Assets/Images/music_icon.png", UriKind.Relative));
        }

        public void LoadSong()
        {
            if (!_IsLoadedSong)
            {
                List<ItemView> list = new List<ItemView>();
                ICollection<MediaSource> mediaSources = MediaSource.GetAvailableMediaSources();
                foreach (MediaSource source in mediaSources)
                {
                    if (source.MediaSourceType == MediaSourceType.LocalDevice)
                    {
                        MediaLibrary library = new MediaLibrary(source);
                        SongCollection songs = library.Songs;
                        foreach (Song song in songs)
                        {
                            ItemView itv = new ItemView(song.Name, song.Artist.Name, _SongImage);
                            list.Add(itv);
                        }
                    }
                }

                _llsSong.ItemsSource = list;
                _IsLoadedSong = true;
            }
        }

        public void LoadArtist()
        {
            if (!_IsLoadedArtist)
            {
                List<ItemView> list = new List<ItemView>();
                ICollection<MediaSource> mediaSources = MediaSource.GetAvailableMediaSources();
                foreach (MediaSource source in mediaSources)
                {
                    if (source.MediaSourceType == MediaSourceType.LocalDevice)
                    {
                        MediaLibrary library = new MediaLibrary(source);
                        ArtistCollection artists = library.Artists;
                        foreach (Artist artist in artists)
                        {
                            ItemView itv = new ItemView(artist.Name, artist.Songs.Count.ToString() + " bài hát", _SongImage);
                            list.Add(itv);
                        }
                    }
                }

                _llsArtist.ItemsSource = list;
                _IsLoadedArtist = true;
            }
        }

        public void LoadAlbum()
        {
            if (!_IsLoadedAlbum)
            {
                List<ItemView> list = new List<ItemView>();
                ICollection<MediaSource> mediaSources = MediaSource.GetAvailableMediaSources();
                foreach (MediaSource source in mediaSources)
                {
                    if (source.MediaSourceType == MediaSourceType.LocalDevice)
                    {
                        MediaLibrary library = new MediaLibrary(source);
                        AlbumCollection albums = library.Albums;
                        foreach (Album album in albums)
                        {
                            ItemView itv = new ItemView(album.Name, album.Songs.Count.ToString() + " bài hát", _SongImage);
                            list.Add(itv);
                        }
                    }
                }

                _llsAlbum.ItemsSource = list;
                _IsLoadedAlbum = true;
            }
        }

        public void LoadContent()
        {

            switch (_CurrentMedia)
            {
                case MEDIA.SONG:
                    LoadSong();
                    _llsSong.Visibility = System.Windows.Visibility.Visible;
                    _llsArtist.Visibility = System.Windows.Visibility.Collapsed;
                    _llsAlbum.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                case MEDIA.ARTIST:
                    LoadArtist();
                    _llsSong.Visibility = System.Windows.Visibility.Collapsed;
                    _llsArtist.Visibility = System.Windows.Visibility.Visible;
                    _llsAlbum.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                case MEDIA.ALBUM:
                    LoadAlbum();
                    _llsSong.Visibility = System.Windows.Visibility.Collapsed;
                    _llsArtist.Visibility = System.Windows.Visibility.Collapsed;
                    _llsAlbum.Visibility = System.Windows.Visibility.Visible;
                    break;
                default:
                    _llsSong.Visibility = System.Windows.Visibility.Collapsed;
                    _llsArtist.Visibility = System.Windows.Visibility.Collapsed;
                    _llsAlbum.Visibility = System.Windows.Visibility.Collapsed;
                    break;
            }
        }

        public void LoadInterface()
        {
            switch (_CurrentMedia)
            {
                case MEDIA.SONG:
                    _txtTile.Text = "Bài hát";
                    break;

                case MEDIA.ALBUM:
                    _txtTile.Text = "Album";
                    break;

                case MEDIA.ARTIST:
                    _txtTile.Text = "Ca sĩ";
                    break;

                default:
                    _txtTile.Text = "";
                    break;
            }
        }

        private void NextMedia()
        {
            switch (_CurrentMedia)
            {
                case MEDIA.SONG:
                    _CurrentMedia = MEDIA.ARTIST;
                    break;

                case MEDIA.ARTIST:
                    _CurrentMedia = MEDIA.ALBUM;
                    break;

                default:
                    _CurrentMedia = MEDIA.SONG;
                    break;
            }
            LoadInterface();
            LoadContent();
        }

        private void PrevMedia()
        {
            switch (_CurrentMedia)
            {
                case MEDIA.SONG:
                    _CurrentMedia = MEDIA.ALBUM;
                    break;

                case MEDIA.ALBUM:
                    _CurrentMedia = MEDIA.ARTIST;
                    break;

                default:
                    _CurrentMedia = MEDIA.SONG;
                    break;
            }
            LoadInterface();
            LoadContent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string gridName = "";
            try
            {
                gridName = NavigationContext.QueryString["parameter"];
            }
            catch
            { }

            switch (gridName)
            {
                case "_grdSong":
                    _CurrentMedia = MEDIA.SONG;
                    break;
                case "_grdArtist":
                    _CurrentMedia = MEDIA.ARTIST;
                    break;
                case "_grdAlbum":
                    _CurrentMedia = MEDIA.ALBUM;
                    break;

                default:
                    _CurrentMedia = MEDIA.SEARCH;
                    break;
            }
            LoadInterface();
            LoadContent();
        }

        private void llsSong_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (_llsSong.SelectedItem == null)
                return;

            string songName = "";
            try
            {
                ItemView ivm = (_llsSong.SelectedItem as ItemView);
                songName = ivm._Name.Text;
            }
            catch { return; }


            Song selectedSong = null;
            using (MediaLibrary ml = new MediaLibrary())
            {
                SongCollection songs = ml.Songs;
                foreach (Song song in songs)
                {
                    if (song.Name == songName)
                    {
                        selectedSong = song;
                        break;
                    }
                }

                if (selectedSong != null)
                {
                    MediaPlayer.Play(selectedSong);
                }
                ml.Dispose();
            }
        }

        private void llsArtist_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (_llsArtist.SelectedItem == null)
                return;

            string artistName = "";
            try
            {
                artistName = (_llsArtist.SelectedItem as ItemView)._Name.Text;
            }
            catch
            {
                return;
            }

            Artist selectedArtist = null;
            using (MediaLibrary ml = new MediaLibrary())
            {
                ArtistCollection artists = ml.Artists;
                foreach (Artist art in artists)
                {
                    if (art.Name == artistName)
                    {
                        selectedArtist = art;
                        break;
                    }
                }
            }
            if (selectedArtist != null)
            {
                MediaPlayer.Play(selectedArtist.Songs);
            }
        }

        private void llsAlbum_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (_llsAlbum.SelectedItem == null)
                return;

            string albumName = "";
            try
            {
                albumName = (_llsAlbum.SelectedItem as ItemView)._Name.Text;
            }
            catch
            {
                return;
            }

            Album selectedAlbum = null;
            using (MediaLibrary ml = new MediaLibrary())
            {
                AlbumCollection albums = ml.Albums;
                foreach (Album album in albums)
                {
                    if (album.Name == albumName)
                    {
                        selectedAlbum = album;
                        break;
                    }
                }
            }
            if (selectedAlbum != null)
            {
                MediaPlayer.Play(selectedAlbum.Songs);
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            _ctrMedia._txtDuration.Text = MediaPlayer.PlayPosition.Duration().ToString(@"mm\:ss");
        }

        private void _OnMediaStateChanged(object sender, EventArgs e)
        {
            switch (MediaPlayer.State)
            {
                case MediaState.Paused:
                    if (_timer.IsEnabled)
                        _timer.Stop();
                    break;
                case MediaState.Playing:
                    if (!_timer.IsEnabled)
                        _timer.Start();
                    break;
                case MediaState.Stopped:
                    if (_timer.IsEnabled)
                        _timer.Stop();
                    break;
            }
        }

        private void _OnActiveSongChanged(object sender, EventArgs e)
        {
            _timer.Interval = new TimeSpan(3333);
            if (!_timer.IsEnabled)
                _timer.Start();
            if (MediaPlayer.Queue.ActiveSong != null)
            {
                _ctrMedia._txtCurrentSong.Text = MediaPlayer.Queue.ActiveSong.Name;
                _ctrMedia.SetPlayButton();
            }
        }

        private void grdSong_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _MouseDownPoint = e.GetPosition(_grdSong);
        }

        private void grdSong_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _MouseUpPoint = e.GetPosition(_grdSong);
            if (_MouseUpPoint.Y >= _MouseDownPoint.Y - 20 && _MouseUpPoint.Y <= _MouseDownPoint.Y + 20
                && _MouseDownPoint.X > _MouseUpPoint.X + 20)
            {
                NextMedia();
            }
            else if (_MouseUpPoint.Y >= _MouseDownPoint.Y - 20 && _MouseUpPoint.Y <= _MouseDownPoint.Y + 20
                && _MouseDownPoint.X < _MouseUpPoint.X - 20)
            {
                PrevMedia();
            }
        }

        private void btnNextTile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NextMedia();
        }

        private void btnPrevTile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            PrevMedia();
        }
    }
}